package com.yanyun.yczyy.api.repository.impl;

import com.yanyun.yczyy.api.entities.EnergyUsedView;
import com.yanyun.yczyy.api.entities.EnergyValue;
import com.yanyun.yczyy.api.entities.TblIOData;
import com.yanyun.yczyy.api.repository.IDynamicDataRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Repository
public class DynamicDataRepository implements IDynamicDataRepository {
    @Override
    public List<TblIOData> supplyAirTemperature() {
        final String sql = "select a.resource_name,a.io_time,a.`value` from tbl_io_data a,\n" + "(select resource_id,max(io_time) io_time from tbl_io_data where io_time >= DATE_ADD(NOW(),interval -12 hour)\t and sys_name ='AHU系统'  and resource_name like '%送风温度'\n" + "group by resource_id) b\n" + "where a.resource_id = b.resource_id and a.io_time = b.io_time\n" + "group by resource_name\n" + "order by resource_name";
        try {
            return yczyy.query(sql, m_IODataMapper);
        } catch (Exception e) {
            log.error("查询送风温度失败:", e);
            return null;
        }
    }

    @Override
    public List<TblIOData> returnAirTemperature() {
        final String sql = "select a.resource_name,a.io_time,a.`value` from tbl_io_data a,\n" +
                "(select resource_id,max(io_time) io_time from tbl_io_data where io_time >= DATE_ADD(NOW(),interval -12 hour)\t and sys_name ='AHU系统'  and resource_name like '%回风温度'\n" +
                "group by resource_id) b\n" +
                "where a.resource_id = b.resource_id and a.io_time = b.io_time\n" +
                "group by resource_name\n" +
                "order by resource_name";
        try {
            return yczyy.query(sql, m_IODataMapper);
        } catch (Exception e) {
            log.error("查询送风温度失败:", e);
            return null;
        }
    }

    @Override
    public List<EnergyUsedView> yiYanWaterUsed() {
        final String sql = "select a.resource_name location,DATE_FORMAT(a.io_time,'%Y-%m-%d %H:00:00') hour,cast(max(a.`value`) as FLOAT) value from tbl_io_data a where io_time >= DATE_ADD(NOW(),interval -24 hour)\t and sys_name ='能耗水表'and resource_name like '医研%'  and device_id = '4183' and length(`value`) = 8\n" +
                "group by a.resource_name,DATE_FORMAT(a.io_time,'%Y-%m-%d %H:00:00')";

        try {
            List<EnergyValue> ret = yczyy.query(sql, m_EnergyValueMapper);
            if (ret.isEmpty()) {
                return null;
            }
            return usedViews(ret);

        } catch (Exception e) {
            log.error("查询医研用水使用失败：", e);
            return null;
        }
    }

    @Override
    public List<EnergyUsedView> menZhenWaterUsed() {
        final String sql = "select a.resource_name location,DATE_FORMAT(a.io_time,'%Y-%m-%d %H:00:00') hour,cast(max(a.`value`) as FLOAT) value from tbl_io_data a where io_time >= DATE_ADD(NOW(),interval -24 hour)\t and sys_name ='能耗水表'and resource_name like '门诊%'  and device_id = '4184' and length(`value`) = 9\n" +
                "group by a.resource_name,DATE_FORMAT(a.io_time,'%Y-%m-%d %H:00:00')";

        try {
            List<EnergyValue> ret = yczyy.query(sql, m_EnergyValueMapper);
            if (ret.isEmpty()) {
                return null;
            }
            return usedViews(ret);

        } catch (Exception e) {
            log.error("查询医研用水使用失败：", e);
            return null;
        }
    }

    @Override
    public List<TblIOData> co1Concentration() {
        final String sql = "select a.resource_name resource_name,max(DATE_FORMAT(a.io_time,'%Y-%m-%d %H:00:00')) io_time,cast(max(a.`value`) as FLOAT) value from  tbl_io_data a where io_time >= DATE_ADD(NOW(),interval -12 hour)\t and sys_name ='环境监测' and resource_name like '%一氧化碳%'\n" +
                "group by a.resource_name\n" +
                "order by a.resource_name,max(DATE_FORMAT(a.io_time,'%Y-%m-%d %H:00:00'))";

        try {
            return yczyy.query(sql, m_IODataMapper);
        } catch (Exception e) {
            log.error("查询送风温度失败:", e);
            return null;
        }
    }

    @Override
    public List<TblIOData> co2Concentration() {
        final String sql = "select a.resource_name resource_name,max(DATE_FORMAT(a.io_time,'%Y-%m-%d %H:00:00')) io_time,cast(max(a.`value`) as FLOAT) value from  tbl_io_data a where io_time >= DATE_ADD(NOW(),interval -12 hour)\t and sys_name ='环境监测' and resource_name like '%二氧化碳%'\n" +
                "group by a.resource_name\n" +
                "order by a.resource_name,max(DATE_FORMAT(a.io_time,'%Y-%m-%d %H:00:00'))";

        try {
            return yczyy.query(sql, m_IODataMapper);
        } catch (Exception e) {
            log.error("查询送风温度失败:", e);
            return null;
        }
    }
    private List<EnergyUsedView> usedViews(List<EnergyValue> values) {
        List<EnergyUsedView> view = new ArrayList<>();
        Map<String, List<EnergyValue>> locationHourGroup = values.stream().filter(a -> a.getValue() > 0).collect(Collectors.groupingBy(EnergyValue::getLocation));

        locationHourGroup.entrySet().stream().filter(a -> a.getValue().size() > 1).forEach(kv -> {
            for (int i = 0; i < kv.getValue().size(); i++) {
                if (i == kv.getValue().size() - 1)
                    return;
                float used = kv.getValue().get(i + 1).getValue() - kv.getValue().get(i).getValue();
                if (used < 0)
                    return;
                EnergyUsedView item = new EnergyUsedView();
                item.setLocation(kv.getValue().get(i).getLocation());
                item.setHour(kv.getValue().get(i).getHour());
                item.setUsed(used);
                view.add(item);
            }
        });
        return view;
    }
    private final RowMapper<TblIOData> m_IODataMapper = new BeanPropertyRowMapper<>(TblIOData.class);
    private final RowMapper<EnergyValue> m_EnergyValueMapper = new BeanPropertyRowMapper<>(EnergyValue.class);
    @Autowired
    JdbcTemplate yczyy;
}
